package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.entity.UserDto;
import com.itheima.reggie.service.IUserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

/**
 * User控制层
 * @author panda
 * @since 2023/1/4 22:30
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private IUserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    //由于在登陆时的俩个接口,登录和手机验证码的接口不能被过滤器拦截,需要在过滤器中添加释放的地址
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session){
        //获取手机号
        String phone = user.getPhone();
        if(StringUtils.isNotEmpty(phone)){
            //生成随机的4位验证码
            String code = ValidateCodeUtils.generateValidateCode(4).toString();
            log.info("code={}",code);

            //调用阿里云提供的短信服务API完成发送短信
            //

            ////需要将生成的验证码保存到Session
            //session.setAttribute(phone,code);
            /**
             * 将手机验证码放入到redis当中,可以设置任意时效
             */
            //将时效设置为5分钟
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);
            return R.success("手机验证码短信发送成功");
        }
        return R.error("短信发送失败");
    }
    @PostMapping("/login")
    public R<String> login(@RequestBody UserDto userDto,
                           HttpSession session ){
        String phone = userDto.getPhone();
        String code = userDto.getCode();
        //通过验证码登录
        log.info("登录的手机号:{},登录的验证码:{}", phone, code);
        ////通过session中的只进行比对,相同的话登陆成功
        //String oldCode = session.getAttribute(phone).toString();
        /**
         * 优化成将验证码和redis中存储的验证码进行对比
         */
        Object oldCode = redisTemplate.opsForValue().get(phone);
        if (oldCode != null && code.equals(oldCode.toString())){
            //再判断用户是否注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getPhone,phone);
            User user = userService.getOne(queryWrapper);
            if (user == null) {
                //没有注册则给新用户注册,
                //那么将user存入新的User,进行注册
                user = new User();
                user.setPhone(phone);
                user.setStatus(1);
                userService.save(user);
            }
            // 注册过就把用户ID存到session中去
            session.setAttribute("user",user.getId());
            //在登录过后在去把验证码删除掉
            redisTemplate.delete(phone);
            return R.success("登陆成功");
        }
        return R.error("验证码错误,登陆失败");

    }
}